// 我的收藏页面
const auth = require('../../../utils/auth')
const { getUserFavorites } = require('../../../api/serviceItems')

Page({
  data: {
    favorites: [],
    loading: false,
    empty: false
  },
  // 全局加载状态
  globalLoading: false,
  globalLoadingText: '用户信息加载中...',

  // 显示全局加载
  showGlobalLoading(text = '用户信息加载中...') {
    const app = getApp()
    app.showGlobalLoading({
      loadingText: text
    })
  },

  // 隐藏全局加载
  hideGlobalLoading() {
    const app = getApp()
    app.hideGlobalLoading()
  },

  // 更新全局加载状态
  updateGlobalLoading(data) {
    this.setData({
      globalLoading: data.globalLoading,
      globalLoadingText: data.globalLoadingText || this.data.globalLoadingText
    })
  },

  onLoad() {
    this.checkLoginStatus()
    this.loadFavorites()
  },

  onShow() {
    this.loadFavorites()
  },

  // 检查登录状态
  checkLoginStatus() {
    try {
      const currentUser = auth.getCurrentUser()
      if (!currentUser || !currentUser.userId) {
        wx.redirectTo({ url: '/pages/auth/login/index' })
        return
      }
    } catch (e) {
      console.error('获取用户信息失败:', e)
      wx.redirectTo({ url: '/pages/auth/login/index' })
    }
  },

  // 加载收藏数据
  async loadFavorites() {
    try {
      this.setData({ loading: true })
      
      // 获取当前用户
      const currentUser = auth.getCurrentUser()
      if (!currentUser || !currentUser.userId) {
        this.setData({
          favorites: [],
          loading: false,
          empty: true
        })
        return
      }

      // 从服务端获取用户收藏列表
      const result = await getUserFavorites(currentUser.userId)
      
      if (result.success && result.data.favorites) {
        const favoriteItems = result.data.favorites.map(item => ({
          id: item.serviceItemId,
          title: item.serviceTitle,
          desc: item.serviceDescription,
          dept: item.serviceDepartment,
          online: item.isOnline,
          appoint: item.isAppointment,
          cateId: item.categoryId,
          categoryName: item.categoryName || this.getCategoryName(item.categoryId)
        }))
        
        this.setData({
          favorites: favoriteItems,
          loading: false,
          empty: favoriteItems.length === 0
        })
      } else {
        this.setData({
          favorites: [],
          loading: false,
          empty: true
        })
      }
    } catch (error) {
      console.error('加载收藏数据失败:', error)
      this.setData({
        favorites: [],
        loading: false,
        empty: true
      })
      wx.showToast({
        title: '加载收藏失败',
        icon: 'none'
      })
    }
  },

  // 获取所有服务项目数据（与服务页面保持一致）
  getAllServiceItems() {
    return [
      // 民政社保
      { id: 'i1', cateId: 'c1', title: '最低生活保障申请', desc: '困难群众最低生活保障资格申请与复核', dept: '民政办', online: true, appoint: false },
      { id: 'i2', cateId: 'c1', title: '临时救助', desc: '突发困难家庭临时救助申领', dept: '民政办', online: true, appoint: true },
      { id: 'i3', cateId: 'c1', title: '特困供养申请', desc: '分散供养、集中供养对象认定', dept: '民政办', online: false, appoint: true },
      { id: 'i4', cateId: 'c1', title: '残疾人两项补贴', desc: '困难残疾人生活补贴、重度护理补贴', dept: '残联联络员', online: true, appoint: false },
      { id: 'i5', cateId: 'c1', title: '养老补贴申请', desc: '老年人生活补贴申请办理', dept: '民政办', online: true, appoint: false },
      
      // 城乡建设
      { id: 'i6', cateId: 'c2', title: '宅基地申请', desc: '宅基地资格审核与建设申请', dept: '村两委', online: false, appoint: true },
      { id: 'i7', cateId: 'c2', title: '危房改造申请', desc: '农村危房改造对象认定与补助', dept: '村建专干', online: true, appoint: false },
      { id: 'i8', cateId: 'c2', title: '房屋建筑施工备案', desc: '农房建设施工备案', dept: '村建专干', online: true, appoint: false },
      { id: 'i9', cateId: 'c2', title: '用地规划咨询', desc: '宅基地、生产用地规划政策咨询', dept: '自然资源协管员', online: false, appoint: true },

      // 农业农村
      { id: 'i10', cateId: 'c3', title: '耕地地力保护补贴', desc: '农户年度耕地保护补贴申领', dept: '农业服务站', online: true, appoint: false },
      { id: 'i11', cateId: 'c3', title: '农机购置补贴', desc: '购机补贴申请与资料初审', dept: '农业服务站', online: true, appoint: false },
      { id: 'i12', cateId: 'c3', title: '高标准农田申报', desc: '高标准农田建设项目意向申报', dept: '农业服务站', online: false, appoint: true },
      
      // 综合治理
      { id: 'i13', cateId: 'c4', title: '矛盾纠纷调解', desc: '群众纠纷调解受理与处理进度查询', dept: '综治办', online: true, appoint: true },
      { id: 'i14', cateId: 'c4', title: '治安事件反映', desc: '治安隐患/事件上报与流转', dept: '网格员', online: true, appoint: false },
      { id: 'i15', cateId: 'c4', title: '重点人员帮扶', desc: '帮扶对象联系与走访预约', dept: '综治办', online: false, appoint: true },

      // 教育卫健
      { id: 'i16', cateId: 'c5', title: '新农合参保咨询', desc: '城乡居民医疗参保与变更咨询', dept: '卫健室', online: false, appoint: true },
      { id: 'i17', cateId: 'c5', title: '计免接种预约', desc: '儿童免疫接种预约登记', dept: '卫健室', online: false, appoint: true },
      { id: 'i18', cateId: 'c5', title: '学生资助申请', desc: '困难学生助学金申请', dept: '村教育协理员', online: true, appoint: false },

      // 证件办理
      { id: 'i19', cateId: 'c6', title: '户籍办理', desc: '户口迁入/迁出申请办理', dept: '派出所', online: true, appoint: false },
      { id: 'i20', cateId: 'c6', title: '居住证明开具', desc: '常住人口居住证明出具', dept: '村委办公室', online: true, appoint: false },
      { id: 'i21', cateId: 'c6', title: '婚育证明', desc: '婚育情况证明开具', dept: '计生专干', online: false, appoint: true },
      { id: 'i22', cateId: 'c6', title: '困难证明', desc: '家庭经济困难证明开具', dept: '民政办', online: true, appoint: false },

      // 公共服务
      { id: 'i23', cateId: 'c7', title: '用水报修', desc: '村内自来水设施故障报修', dept: '水务协管', online: true, appoint: true },
      { id: 'i24', cateId: 'c7', title: '路灯报修', desc: '公共照明故障上报与处理', dept: '村建专干', online: true, appoint: false },
      { id: 'i25', cateId: 'c7', title: '环境卫生投诉', desc: '垃圾清运、卫生死角反馈', dept: '环卫协管', online: true, appoint: false },

      // 生态环保
      { id: 'i26', cateId: 'c8', title: '秸秆焚烧举报', desc: '发现露天焚烧立即上报', dept: '生态环保员', online: true, appoint: false },
      { id: 'i27', cateId: 'c8', title: '河湖巡查上报', desc: '巡河巡湖发现问题上报', dept: '河长办协管', online: true, appoint: false },
      { id: 'i28', cateId: 'c8', title: '散养家禽规范指导', desc: '散养家禽管理与整改指导预约', dept: '生态环保员', online: false, appoint: true }
    ]
  },

  // 获取分类名称
  getCategoryName(cateId) {
    const categories = {
      'c1': '民政社保',
      'c2': '城乡建设', 
      'c3': '农业农村',
      'c4': '综合治理',
      'c5': '教育卫健',
      'c6': '证件办理',
      'c7': '公共服务',
      'c8': '生态环保'
    }
    return categories[cateId] || '其他'
  },

  // 点击收藏项目
  onTapItem(e) {
    console.log('点击事件触发:', e)
    const id = e.currentTarget.dataset.id
    console.log('获取到的ID:', id)
    
    if (!id) {
      wx.showToast({
        title: '数据错误，请重试',
        icon: 'none'
      })
      return
    }
    
    // 显示点击提示
    console.log(`点击了收藏项目: ${id}`)
    
    // 根据事项ID直接跳转到对应的业务办理页面
    const pageMap = {
      i1: '/pages/service/civil-affairs/apply/index',      // 最低生活保障申请
      i2: '/pages/service/temp-aid/index',   // 临时救助申请
      i3: '/pages/service/extreme-support/index', // 特困供养审核
      i4: '/pages/service/disability-subsidy/index', // 残疾人两项补贴
      i5: '/pages/service/pension-subsidy/index', // 养老补贴申请
      i6: '/pages/service/homestead-approval/index', // 宅基地申请
      i7: '/pages/service/danger-house-reform/index', // 危房改造申请
      i8: '/pages/service/construction-record/index', // 房屋建筑施工备案
      i9: '/pages/service/land-planning-consult/index', // 用地规划咨询
      i10: '/pages/service/farmland-protection-subsidy/index', // 耕地地力保护补贴
      i11: '/pages/service/agri-equipment-subsidy/index', // 农机购置补贴
      i12: '/pages/service/high-standard-farmland-declare/index', // 高标准农田申报
      i13: '/pages/service/dispute-mediation/index', // 矛盾纠纷调解
      i14: '/pages/service/public-security-report/index', // 治安事件反映
      i15: '/pages/service/key-person-assistance/index', // 重点人员帮扶
      i16: '/pages/service/medical-enroll-consult/index', // 新农合参保咨询
      i17: '/pages/service/vaccination-appointment/index', // 计免接种预约
      i18: '/pages/service/student-aid-apply/index', // 学生资助申请
      i19: '/pages/service/hukou-apply/index', // 户籍办理
      i20: '/pages/service/residence-certificate/index', // 居住证明开具
      i21: '/pages/service/marriage-certificate/index', // 婚育证明
      i22: '/pages/service/difficulty-certificate/index', // 困难证明
      i23: '/pages/service/water-repair/index', // 用水报修
      i24: '/pages/service/streetlight-repair/index', // 路灯报修
      i25: '/pages/service/environment-complaint/index', // 环境卫生投诉
      i26: '/pages/service/straw-burning-report/index', // 秸秆焚烧举报
      i27: '/pages/service/river-patrol-report/index', // 河湖巡查上报
      i28: '/pages/service/poultry-management/index', // 散养家禽规范指导
    }
    const target = pageMap[id]
    if (target) {
      wx.navigateTo({ 
        url: target,
        fail: (err) => {
          console.error('页面跳转失败:', err)
          wx.showToast({
            title: '页面跳转失败',
            icon: 'none'
          })
        }
      })
      return
    }
    // 若无对应在线办理页面，结合事项属性给出提示
    const item = this.data.favorites.find(it => it.id === id)
    if (item && item.appoint && !item.online) {
      wx.showToast({ title: '该事项支持预约到村委办理', icon: 'none' })
    } else {
      // 先尝试跳转到服务详情页面
      wx.navigateTo({
        url: `/pages/service/detail/index?id=${id}`,
        fail: () => {
          wx.showToast({ title: '该服务的在线办理功能正在开发中', icon: 'none' })
        }
      })
    }
  },

  // 取消收藏
  async onRemoveFavorite(e) {
    const id = e.currentTarget.dataset.id
    const item = this.data.favorites.find(it => it.id === id)
    
    if (!item) return

    // 获取当前用户
    const currentUser = auth.getCurrentUser()
    if (!currentUser || !currentUser.userId) {
      wx.showToast({
        title: '请先登录',
        icon: 'none'
      })
      return
    }

    wx.showModal({
      title: '确认取消收藏',
      content: `确定要取消收藏"${item.title}"吗？`,
      confirmText: '取消收藏',
      confirmColor: '#ef4444',
      cancelText: '保留',
      success: async (res) => {
        if (res.confirm) {
          try {
            // 调用服务端API取消收藏
            const { removeFavorite } = require('../../../api/serviceItems')
            const result = await removeFavorite(id, currentUser.userId)
            
            if (result.success) {
              // 重新加载收藏列表
              await this.loadFavorites()
              
              wx.showToast({
                title: '已取消收藏',
                icon: 'success'
              })
            } else {
              wx.showToast({
                title: result.message || '取消收藏失败',
                icon: 'none'
              })
            }
          } catch (error) {
            console.error('取消收藏失败:', error)
            wx.showToast({
              title: '取消收藏失败',
              icon: 'none'
            })
          } finally {
                    // 数据加载完成，隐藏全局加载
        this.hideGlobalLoading();
        }
        }
      }
    })
  },

  // 返回上一页
  onBack() {
    wx.navigateBack()
  },

  // 跳转到服务页面
  onGoToService() {
    wx.switchTab({
      url: '/pages/service/index/index'
    })
  },


  // 刷新功能
  onRefresh() {
    this.loadFavorites()
    wx.showToast({
      title: '刷新成功',
      icon: 'success',
      duration: 1500
    })
  },

  // 下拉刷新
  onPullDownRefresh() {
    this.loadFavorites()
    setTimeout(() => {
      wx.stopPullDownRefresh()
    }, 1000)
  }
})
